/**
 * 
 */
package cn.com.fattiger.framework.remoting.thread;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * ThreadFactory
 * @author fattiger.xiaoyang
 * @date 2016/01/28
 * @qqGroup 48450434
 */
public class NamedThreadFactory implements ThreadFactory {
	
	private static final AtomicInteger poolNo = new AtomicInteger(1);

    private final AtomicInteger threadNo = new AtomicInteger(1);
    
    private final ThreadGroup group;
    
    private final String prefix;
    
    private final boolean daemon;
    
    public NamedThreadFactory() {
        this("Fattiger");
    }
    
    public NamedThreadFactory(String name) {
        this(name, false);
    }
    
    public NamedThreadFactory(String preffix, boolean daemon) {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        prefix = preffix + "-pool-" + poolNo.getAndIncrement() + "-thread-";
        this.daemon = daemon;
    }
    
	@Override
	public Thread newThread(Runnable r) {
		Thread t = new Thread(group, r, prefix + threadNo.getAndIncrement(), 0);
        t.setDaemon(daemon);
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
	}
}
